<template>
  <div :class="tab">
    <div class="headline">
      <span></span>我{{tab=='games-join'?'参加':'创建'}}的比赛
    </div>
    <a class="game" href="javascript:;" v-for="item in gameList" @click.stop.prevent="gameDetail(item)">
      <div class="official-game-icon" v-if='item.gameType == "NETDS" || item.gameType == ""'>排名赛</div>
      <div class="team-game-icon" v-else-if='item.gameType == "TDS"'>团队赛</div>
      <div class="huge-game-icon" v-else-if='item.gameType == "CLS"'>超级赛</div>
      <div class="huge-game-icon" v-else-if='item.gameType == "JYS"'>精英赛</div>
      <div class="huge-game-icon" v-else-if='item.gameType == "QGS"'>全国赛</div>
      <div class="official-game-icon" v-else-if='item.gameKind == "1"'>官方</div>
      <div class="text-center">
        <img src="~assets/images/shuyezuo@3x.png">
        <div class="games-block-content">
          <div class="game-name">{{item.upGameName || item.gameName}}</div>
          <div class="date">
            <span>{{item.beginDate}} - {{item.endDate}}</span>
            <b>
              <i class="arrow-right1"></i><i class="arrow-right2"></i>
            </b>
          </div>
        </div>
        <img src="~assets/images/shuyeyou@3x.png">
      </div>

      <div class="game-row">

        <div class="game-row-item ratio" v-if="item.gameStep == 3 || item.gameStep == 4">
          <div class="key">收益率</div>
          <div class="value" :class="item.totalProfit<0 ? 'negative' : 'positive'">{{item.totalProfit}}%</div>
        </div>
        <div class="game-row-item" v-else>
          <div class="key">参加人数</div>
          <div class="value color-blue">
            {{item.gameAttendPerson}}<span class="color-gray" v-if="item.joinBeginDate && item.joinBeginDate!=0">/{{item.gameMaxLimit}}</span>
          </div>
        </div>

        <div class="game-row-item">
          <template v-if="item.gameStep == 3 || item.gameStep == 4">
            <div class="key">我的排名</div>
            <div class="value color-red" v-text="item.ranknum <= 0?'--':item.ranknum"></div>
          </template>
          <div class="value color-red " v-if="item.gameStep <3">{{item.timeClosing}}</div>
        </div>

        <div class="game-row-item" v-if="item.gameType == 'TDS' && item.gameStep > 2">
            <div class="key">我的团队</div>
            <div class="value">{{item.gameName}}</div>
        </div>

        <div class="game-row-item statue">
          <div class="key" :class="{'color-blue':item.gameStep == 1,'color-red':item.gameStep == 3}">
            {{item.tips}}
          </div>
        </div>

      </div>

      <div class='forward'>
        <i class='iconfont icon-xiangyou'></i>
      </div>
    </a>
    <div class="zero-game" v-if="gameList.length == 0 && !firstLoading">
      <div class="content" v-if="error == ''">
        <div class="niu">
          <img src="~assets/images/trade/meicanjiabisai.png" v-if="tab=='games-join'">
          <img src="~assets/images/trade/meibisai.png" v-if="tab=='games-create'">
        </div>
        <div class="submit" @click.stop.prevent="joinGame" v-if="tab=='games-join'">
          立即参加
        </div>
        <div class="submit" @click.stop.prevent="createGame" v-if="tab=='games-create'">
          立即创建
        </div>
      </div>
      <div class="no-data" v-else>
        {{error}}
      </div>
    </div>
    <div v-if="firstLoading" class="loading">
      <img src="~assets/images/loading.gif" style="width:40px;height:40px;"/>
      <div>加载中</div>
    </div>
  </div>
</template>

<script>
  import RemoteDAO from 'common/remoteDAO'
  import CommonUtil from 'common/common.util'
  import LocalDAO from 'common/localDAO'
  import _ from 'underscore'

  export default {
    data () {
      return {
        gameList: [],
        error: '',
        dateNow: '',
        timeNow: '',
        baseDateTime: '',
        index: 0,
        timeschel: '',
        firstLoading: true
      }
    },
    props: {
      tab: {
        type: String
      }
    },
    created:function(){
      this.fetchData();
    },
    mounted: function () {
      if (this.page = 'account') {
        this.timeNow = Number(CommonUtil.getTodayFormatTime());
        this.dateNow = Number(CommonUtil.getTodayFormatDate());
        this._countdownTime();
      }
    },
    beforeDestroy: function () {
      if (this.page = 'account') {
        clearInterval(this.timeschel);
      }
    },
    methods: {
      fetchData () {
        var actionFlag = this.tab == 'games-join' ? '1' : '2';
        let self = this;
        // 查询我创建的比赛
        RemoteDAO.callGT1008(function (resp) {
          if (Number(resp.error) === 0) {
            let dateNow = resp.data.body.date;
            // 查询我的比赛
            RemoteDAO.callHB002(self.userCode, actionFlag, '200', '0', '0', function (response) {
              let gameList = [];
              if (response.error == 0) {
                if (actionFlag == '1') {
                  self.$root.eventHub.$emit('getGamesJoinNum', response.data.body.length)
                } else if (actionFlag == '2') {
                  self.$root.eventHub.$emit('getGamesCreateNum', response.data.body.length)
                }
                gameList = [];
                _.each(response.data.body, function (item, index) {
                  let object = {}
                  object.upGameId = item.UP_GAME_ID
                  object.gameId = item.GAME_ID;
                  object.upGameName = item.UP_GAME_NAME;
                  object.gameName = item.GAME_NAME;
                  object.gameStatus = item.GAME_STATUS;
                  object.gameStep = item.GAME_STEP;
                  object.gameKind = item.GAME_KIND;
                  object.gameType = item.GAME_TYPE;
                  object.createUser = item.CREATE_USER;
                  object.gameAttendPerson = item.GAME_ATTEND_PERSON;
                  object.gameMaxLimit = item.GAME_MAX_LIMIT;
                  object.BEGIN_DATE = item.BEGIN_DATE;
                  object.END_DATE = item.END_DATE;
                  object.beginDate = CommonUtil.formatDatePoint(item.BEGIN_DATE);
                  object.endDate = CommonUtil.formatDatePoint(item.END_DATE);
                  object.joinBeginDate = item.JOIN_BEGIN_DATE;
                  object.joinEndDate = item.JOIN_END_DATE;
                  object.ranknum = item.ranknum;
                  object.totalProfit = CommonUtil.toFixed(item.total_floatprofit, 2);
                  if (item.total_floatprofit >= 0) {
                    object.totalProfit = '+' + object.totalProfit
                  }
                  object.timeClosing = '----';
                  object.newPlayers = '--';

                  object.tips = ''
                  //DELETE为1，比赛直接无效
                  if (item.DELETE == '1') {
                    object.gameStep = '5';
                    object.tips = '已失效';
                  } else if (object.gameStatus == '0'){
                    object.tips = '待审核';
                  } else if (object.gameStep == '0' ) {
                    object.tips = '未开放报名';
                  } else if (object.gameStep == '1') {
                    object.tips = '报名中';
                  } else if (object.gameStep == '2') {
                    object.tips = '报名结束';
                  } else if (object.gameStep == '3') {
                    object.tips = '进行中';
                  } else if (object.gameStep == '4') {
                    object.tips = '已结束';
                  } else if (object.gameStep == '5') {
                    object.tips = '已失效';
                  } else if (object.gameStatus == '2') {
                    object.tips = object.tips = '审核中';
                  } else if (object.gameStatus == '3') {
                    object.tips = object.tips = '已停赛';
                  } else if (object.gameStatus == '4') {
                    object.tips = object.tips = '已删除';
                  }

                  let startTime = Date.parse(CommonUtil.formatDate(object.joinEndDate));
                  let endTime = Date.parse(CommonUtil.formatDate(dateNow + '')); //new Date().getTime();
                  let daysRemaining = CommonUtil.dateDiff(startTime, endTime);
                  if (daysRemaining > 0) {
                    object.daysRemaining = Math.ceil(daysRemaining);
                  } else if (daysRemaining == 0) {
                    object.daysRemaining = '今';
                  } else {
                    object.daysRemaining = '--';
                  }

                  gameList.push(object)
                });
                gameList.sort((a, b) => {
                  return a.END_DATE > b.END_DATE ? -1 : 1
                })
                self.firstLoading = false;
                self.gameList = gameList;
                self.error = '';
              } else {
                self.firstLoading = false;
                self.error = response.data
              }
            });
          }
        })
      },
      joinGame(){
        this.$router.push('/game')
      },
      createGame(){
        let kv = {"usercode": LocalDAO.getUserCode()}
        TDAPP.onEvent("21017","",kv)
        TDAPP.send()
        this.$router.push('/game/buildgame')
      },
      gameDetail (item){
        if (item.gameType === 'TDS') {
          this.$router.push({ path: '/team-game/game-detail', query: { gameId: item.upGameId, gameName: item.upGameName }});
        } else {
          this.$router.push({path: '/game/gamedetail', query: {gameId: item.gameId}});
        }
      },
      _countdownTime(){
        var self = this;
        RemoteDAO.callGT1008(function (response) {
          if (response.error == "0") {
            self.timeNow = response.data.body.time;
            self.dateNow = response.data.body.date;
          }
          var time1 = (CommonUtil.formatDate(self.dateNow) + " " + CommonUtil.formatTime(self.timeNow)).toString();
          self.baseDateTime = new Date(time1.replace(/-/g, "/")); // 1991/11/11 11:11:12 兼容各浏览器的new Date()

          self.timeschel = setInterval(function () {
            if (typeof self.index === "undefined") {
              self.index = 0;
            }
            _.each(self.gameList, function (item, index) {
              var beginDate = item.BEGIN_DATE;
              var time2 = (CommonUtil.formatDate(beginDate) + " 00:00:00").toString();
              var endTime = new Date(time2.replace(/-/g, "/")); // 比赛开始时间
              var nowTime = self.baseDateTime;
              var t = endTime.getTime() - nowTime.getTime() - 1000 * self.index;
              var d = 0, h = 0, m = 0, s = 0;
              if (t >= 0) {
                d = Math.floor(t / 1000 / 60 / 60 / 24);
                h = Math.floor(t / 1000 / 60 / 60 % 24);
                m = Math.floor(t / 1000 / 60 % 60);
                s = Math.floor(t / 1000 % 60);
              }
              if (h < 10) {
                h = "0" + h;
              }
              if (m < 10) {
                m = "0" + m;
              }
              if (s < 10) {
                s = "0" + s;
              }
              item.timeClosing = d + "天" + h + ":" + m + ":" + s;
            });
            self.index++;
          }, 1000);
        });
      }
    }
  }
</script>

<style scoped>
  .games-join {
    padding-top: 10px;
  }

  .games-join .game:last-child {
    border-bottom: 1px solid #E7E7E7;;
  }

  .games-create {
    margin: 0;
    padding: 10px 0 32px;
  }

  .headline > span {
    border-left: 1px solid #FD5400;
    border-right: 2px solid #FD5400;
  }

  .niu {
    text-align: center;
    margin: 24px 0 17px;
  }

  .submit {
    color: #FFFFFF;
    font-size: 16px;
    border-radius: 5px;
    width: 80%;
    text-align: center;
    margin: 0 auto;
    height: 36px;
    line-height: 36px;
    background: #FF5760;
  }

  .value {
    font-size: 17px;
  }

  .loading{
    text-align: center;
    color:#999999;
  }

  .game-row{
    display: flex;
    justify-content: space-around;
    width: 100%;
  }
  .game-row-item{
    text-align: center;
    display: flex;
    flex: 1;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    min-width: 0;
  }
  .game-row-item >div {
    text-align: center;
    white-space: nowrap;
    padding: 0 2px;
    width: 100%;
  }
  .value{
    font-size: 17px;
    overflow: hidden;
    text-overflow: ellipsis;
  }

</style>
